import api from '@/api/dispatcher'
import { $message } from '@/common/utils'
import {objectToHttpQuery, encrypt, parseJwt} from './utils/transformer'

const user = {
  state: {
    userInfo: {},
    userId: '',
    role: '', // 新增角色字段
    userList: [],
  },
  mutations: {
    setUserInfo(state, data) {
      state.userInfo = data
    },
    setUserId(state, data) {
      state.userId = data
    },
    setRole(state, role) {   // 存储角色
      state.role = role;
    },
    setUsersInfo(userList,data){
      console.log("打印信息"+data)
      userList = data
    }
  },
  actions: {
    userLogin: async ({ commit }, data) => {
      const res = await api.getPublicKey()
      const publicKey =
        res.status === 200 ? res.data.msg : 'get public key error'
      data['password'] = encrypt(data['password'], publicKey)
      // console.log('jsencrypt', data)
      const {
        headers,
        status,
        data: { msg }
      } = await api.login(objectToHttpQuery(data))
      if(status !== 200){
        $message(msg, 'error')

      }
      const token = headers['coin-token']
      localStorage.setItem('coin-token', token)
      // 解析 JWT
      const tokens = localStorage.getItem('coin-token');
      if (tokens && status === 200) {
        const payload = parseJwt(tokens);
        const username = payload.id;
        const role = payload.roles; // 解析角色

        commit('setUserId', username);
        commit('setRole', role); // 存入 Vuex
        localStorage.setItem('user-role', role); // 避免刷新丢失

        // 假设载荷中包含 username 和 role 字段
        // console.log('用户名:', username);
        // console.log('角色:', role);

        $message(msg, status === 200 ? 'success' : 'error')
        return status === 200
      }
    },
    userRegister: async (_, data) => {
      const res = await api.getPublicKey()
      const publicKey =
          res.status === 200 ? res.data.msg : 'get public key error'
      data['password'] = encrypt(data['password'], publicKey)
      const {
        status,
        data: { msg }
      } = await api.register(data)
      $message(msg, status === 200 ? 'success' : 'error')
      return status === 200
    },
    getUserInfo: async ({ commit }) => {
      const res = await api.userInfo()
      if (res.status === 200) {
        commit('setUserInfo', res.data)
        commit('setUserId', res.data.id)
        return true
      }
      return false
    },
    updateUserInfo: async (_, data) => {
        const res = await api.updateUserInfo(data);
        const { status, data: { msg } } = res;
        $message(msg, status === 200 ? 'success' : 'error')
        return status === 200;
      },
    // 保持与updateUserInfo一致的风格实现getUserList
    getUserList: async () => {
      try {
        const res = await api.getUserList();
        if(res.status === 200){
          return res.data
        }

      } catch (error) {
        console.error('获取用户列表出错:', error);
        $message('网络异常，获取用户列表失败', 'error');
        return []; // 异常时返回空数组，避免页面报错
      }
    },
    // 重置密码
    resetPassword: async (_, data) => {
      const res = await api.resetPassword(data);
      const {status, data: {msg}} = res;
      $message(msg, status === 200 ? 'success' : 'error');
      return status === 200;

    }

  },
  getters: {
    userInfo: state => state.userInfo,
    userId: state => state.userId,

    role: state => state.role  // 取出角色信息
  },

}

export default user
